

var templateApproveUtils = {
    isCMPShell : function(){
        return cmp.platform.CMPShell;
    },
    getBackURL:function(){
        return templateApproveUtils.getHrefParam("backURL");
    },
    getQueryString : function(){
        var s = window.location.search;
        if(s){
            //去掉文号
            s = "&" + s.substring(1);

            //cmp路径里面的特殊字符
            s = s.replace(/&cmphistoryuuid=\d+/i, "");
        }
        return s + window.location.hash;
    },
    getHrefParam:function(name){
        var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
        var s = window.location.search;
        if(!s){
            s = window.location.hash;
        }
        if(s){
            var r = s.substr(1).match(reg);
            if(r!=null)
                return  unescape(r[2]);
        }
        return "";
    },/** 过滤emoji字符 **/
    getHrefQuery: function ()  {
        var url = window.location.search,
            reg_url = /^\?([\w\W]+)$/,
            reg_para = /([^&=]+)=([\w\W]*?)(&|$|#)/g,
            arr_url = reg_url.exec(url),
            ret = {};
        if (arr_url && arr_url[1]) {
            var str_para = arr_url[1], result;
            while ((result = reg_para.exec(str_para)) != null) {
                ret[result[1]] = result[2];
            }
        }
        return ret;
    },
    filterUnreadableCode : function(val){
        if(!val){
            return val;
        }
        //ios输入中文只输入拼音不选汉字时特殊字符进行替换
        val = val.replace(/\u2006/g, " ");//8203特殊字符

        return val;

    },
    getDefaultImage : function(){
        return "/meeting/img/defaultMeetingRoom.jpg";
    },
    //处理ajax异常
    dealError : function(obj, errmsg, completeCallback){
        var cmpHandled = cmp.errorHandler(obj);
        if(!cmpHandled){
            if(errmsg){
                _alert(errmsg, completeCallback);
            }else{
                _alert(cmp.i18n("meeting.exception.reqException"));
            }
        }
    }
}

/**
 * 缓加载工具类
 */
var LazyUtil = (function(){

    //缓加载机制
    var lazyStack = {};
    var lazyBindIndex = 0;
    var lazyBindStack = {}
    var lazyUnfinish = 0;
    function LazyTool(){}
    LazyTool.prototype.addLazyStack = function(item){

        /**
         * item.code 字符串 | 堆栈标识
         * item.depend 字符串 | 依赖的js
         * item.dependModel strong/强关联，必须等父任务执行完成后在进行加载  weak/若关联，加载顺序没关系（默认值）
         * item.css 数组 | css数组
         * item.js  数组 | js数组
         *
         */
        if(item.code){
            var i = lazyStack[item.code];
            if(!i){
                item.loaded = false;
                item.isLoading = false;
                lazyStack[item.code] = item;

                lazyUnfinish++;

            }else{
                console.warn("重复设置懒加载, code=" + item.code);
            }
        }else{
            alert(cmp.i18n("collaboration.exception.setException"));
        }
    };

    //启动懒加载
    LazyTool.prototype.startLazy = function(groups){

        for(var k in lazyStack){

            var thisI = lazyStack[k], _this = this;
            if(thisI.loaded || thisI.isLoading){
                continue;
            }
            //按组加载
            if(groups && thisI.groups != groups){
                continue;
            }
            thisI.isLoading = true;

            function loadThis(i){
                if(i.css && i.css.length > 0){
                    cmp.asyncLoad.css(i.css);
                }
                if(i.js && i.js.length > 0){
                    //console.log("开始加载:" + i.js);
                    cmp.asyncLoad.js(i.js, function(){
                        //console.log("完成加载:" + i.js);
                        _this._onJSLoad(i);
                    });
                }else{
                    _this._onJSLoad(i);
                }
            }

            if(thisI.depend && thisI.dependModel === "strong"){
                (function(child){
                    _this.addLoadedFn(child.depend, function(){
                        loadThis(child);
                    });
                })(thisI);
            }else{
                loadThis(thisI);
            }
        }
    };

    /**
     * 是否全部加载完成
     */
    LazyTool.prototype.isFinishAll = function(){
        return lazyUnfinish == 0;
    }

    /**
     * js加载完成后执行脚本
     */
    LazyTool.prototype._onJSLoad = function(i){

        lazyUnfinish--;

        var _this = this;
        i.loaded = true;
        if(i.functions && i.functions.length > 0){
            var checkRet = _this.isLoadChain(i.code);
            if(checkRet.finish){
                for(var j = 0; j < i.functions.length; j++){
                    i.functions[j]();
                }
                i.functions = [];
            }else{
                //事件转移
                for(var j = 0; j < i.functions.length; j++){
                    //console.log("事件转移:" + i.code + " to " + checkRet.code);
                    _this.addLoadedFn(checkRet.code, i.functions[j]);
                }
                i.functions = [];
            }
        }
    }

    //加载脚本加载完成后
    LazyTool.prototype.addLoadedFn = function(code, fn){
        //console.log("接收转移事件:code=" + code + " fn=" + fn);
        var i = lazyStack[code], _this = this;
        if(i){
            var checkRet = _this.isLoadChain(i.code);
            if(checkRet.finish){
                fn();
            }else{
                if(checkRet.code == i.code){
                    i.functions = i.functions || [];
                    i.functions.push(fn);
                }else{
                    //转移
                    _this.addLoadedFn(checkRet.code, fn);
                }
            }
        }else{
            fn();
        }
    };

    /**
     * 校验懒加载是否加载完成了
     * @param code
     */
    LazyTool.prototype.isLoad = function(code){

        var i = lazyStack[code];
        if(i){
            return this.isLoadChain(i.code).finish;
        }
        return true;
    }

    //校验依赖路径是否加载完成
    LazyTool.prototype.isLoadChain = function(code){

        if(!code){
            return {
                "finish" : true
            };
        }else{
            var i = lazyStack[code];
            if(!i.loaded){
                return {
                    "finish" : false,
                    "code" : code
                };
            }else{
                return this.isLoadChain(i.depend);
            }
        }
    };

    /** 延迟点击事件提醒  **/
    LazyTool.prototype._lazyBindInfo = function(){
        _alert(cmp.i18n("collaboration.page.lable.onloading"));//页面正在加载，请稍后点击.
    }

    /**
     *
     * 延迟绑定事件
     *
     **/
    LazyTool.prototype.lazyBindEven = function(lazyCods, ele, event, fn, useCapture){

        if(!lazyCods){
            ele.addEventListener(event, fn, useCapture);
        }else{
            var codes = lazyCods.split(",");

            //添加默认事件
            ele.addEventListener(event, this._lazyBindInfo, useCapture);

            var bindKey = "lazy_bind_" + (lazyBindIndex++);
            lazyBindStack[bindKey] = codes.length;

            for(var i = 0; i < codes.length; i++){

                (function(_this, lazyBindKey, lazyCode, ele, event, fn, useCapture){

                    _this.addLoadedFn(lazyCode, function(){

                        var leftSize = lazyBindStack[lazyBindKey] - 1;
                        if(leftSize < 1){
                            ele.removeEventListener(event, _this._lazyBindInfo, useCapture);
                            ele.addEventListener(event, fn, useCapture);
                            delete lazyBindStack[lazyBindKey];
                        }

                        _this = null;
                        lazyBindKey = null;
                        ele = null;
                        event = null;
                        fn = null;
                        useCapture = null;
                    });

                })(this, bindKey, codes[i], ele, event, fn, useCapture);
            }
        }

    };

    return new LazyTool();
})();
